package aaaTimer;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import javax.imageio.ImageIO;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

import aaBaolilo.ImageDemo;
import aaBaolilo.LoginAndPub;
import aaBaolilo.OcrX;
import aaaBrowser.CaptX;
 
import aaaCfg.Ioc4timer;
import aaaCfg.IocX;

import com.attilax.Closure;
import com.attilax.core;
import com.attilax.db.DBX;
import com.attilax.io.filex;
import com.attilax.io.pathx;
import com.attilax.lang.ClipboardUtil;
import com.attilax.time.timeUtil;
import com.attilax.timer.timerTask;
import com.attilax.ui.atiBrowserExample;
import com.attilax.util.timeTester;
import com.google.inject.Inject;

/**q55 mofify
 * aaaTimer.MainLook public static String USERNAME = "use2015"; //UU u public
 * static String PASSWORD = "000000";
 * 
 * @author Administrator
 * 
 * aaaTimer.get_data
 *
 */
public class BoxService {

	public BoxService() {
		// this.capt=new CaptX();
	}

	// public static void main(String[] args) {
	//
	// }
	public   int spanSec;

	public static void main(String[] args) throws IOException {
   System.out.println("");
		FileInputStream fis = new FileInputStream(new File(
				pathx.classPathParent() + "/db_timer.ini"));
		Properties properties = new Properties();
		properties.load(fis);
		// pro.
		String spanSec_s = properties.getProperty("spanSec").trim();
	

		

		BoxService boxService = Ioc4timer.getBean(BoxService.class);
		boxService.spanSec = Integer.parseInt(spanSec_s);
		boxService.open();

	}

	protected   void reduceTimer() {
		System.out.println("--reduce timer"+timeUtil.Now_CST());
		DBX dx = Ioc4timer.getBean(DBX.class);
		List<Map> li = (dx
				.execSql("select * from timer_tab where timex>0 order by `no`  limit 100 "));
		System.out.println("--catch to data size:" + li.size());
		for (Map map : li) {
			try {
				int tim = (Integer) map.get("timex");
				int now_tim = tim - spanSec;
				if (now_tim < 0)
					now_tim = 0;
				 setTime(map.get("no").toString(),
						String.valueOf(now_tim));
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}

	Display display;
	static atiBrowserExample atiBrowserExampleinstance;

	private void open() {
		
		
		Timer timer = new Timer();

		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				try {
					reduceTimer();
					System.out.println("timer");
					execMeth_AysGui(new Runnable() {
						public void run() {
							atiBrowserExampleinstance.browser
									.execute("window.location.reload();");
						}
					}, "");
				} catch (Exception e) {
					e.printStackTrace();
				}
			

			}
		}, 0, spanSec * 1000);
		
		
		
		display = new Display();
		Shell shell = new Shell(display);
		shell.setLayout(new FillLayout());
		shell.setText("Browser example");
		// shell.setVisible(false);
		// shell.setSize(1, 1);
		atiBrowserExampleinstance = new atiBrowserExample(shell);

		shell.open(); // shell.setVisible(false);

		// core.execMeth_Ays(new Runnable() {
		//
		// @Override
		// public void run() {
		// atiBrowserExampleinstance.addProgressListener(pathx
		// .classPath(LoginAndPub.class) + "\\login.js");
		// atiBrowserExampleinstance
		// .gotoUrl("http://demo.destoon.com/v5.0/member/login.php?a0");
		//
		// }
		// }, "--");

		regJsCallbackMeth();

		// atiBrowserExampleinstance.ini();

		// atiBrowserExampleinstance.addProgressListener(pathx
		// .classPath(LoginAndPub.class) + "\\login.js");

		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		// icon.dispose();
		atiBrowserExampleinstance.dispose();
		display.dispose();
	}

	private void regJsCallbackMeth() {
		core.execMeth_Ays(new Runnable() {

			@Override
			public void run() {
				System.out.println("=-ajsy");
				display.getDefault().asyncExec(new Runnable() {
					@Override
					public void run() {

						// atiBrowserExampleinstance
						// .gotoUrl("http://www.baidu.com");
						String urlgoto = "file:///"
								+ pathx.classPathParent_jensyegeor()
								+ "/Timer/timer.html";
						System.out.println(urlgoto);
						atiBrowserExampleinstance.gotoUrl(urlgoto);
						// atiBrowserExampleinstance.addProgressListener(
						// pathx.classPath(MainLook.class)
						// + "\\reg_test.js", new Closure() {
						//
						// @Override
						// public Object execute(Object arg0)
						// throws Exception {
						// //pub();
						//
						// return null;
						// }
						//
						// });
						atiBrowserExampleinstance.regJsCallbackMeth(
								"getTimerData", new Closure() {

									@Override
									public Object execute(Object arg0)
											throws Exception {
										// setCaptch ();
										return data();
									}

								});
						atiBrowserExampleinstance.regJsCallbackMeth("setTime",
								new Closure<List, Object>() {

									@Override
									public Object execute(List arg0)
											throws Exception {
										// setCaptch ();
										return setTime(arg0);
									}

								});

						atiBrowserExampleinstance.gotoUrl();

					}
				});

			}
		}, "");
	}

	CaptX capt;

	private Object setTime(List arg0) {
		try {

			String no = arg0.get(0).toString();
			String tim = arg0.get(1).toString();

			List li = setTime(no, tim);
			return core.toJsonStrO88(li);
		} catch (Exception e) {
			e.printStackTrace();
			return core.toJsonStrO88(e);
		}

	}

	private List setTime(String no, String tim) {
	 
		String s = "update timer_tab set timex=@t where no='@no'";

		s = s.replaceAll("@t", tim).replaceAll("@no", no);
		System.out.println(s);
		List li = dx.execSql(s);
		return li;
	}
	
	@Inject
	DBX dx;
	@SuppressWarnings("all")
	private Object data() {
		
		
		List<Map> li = dx
				.execSql("select * from timer_tab  order by id limit 40 ");
		for (int i = 0; i < li.size(); i++) {
			try {
				Map m = li.get(i);
				Date dt = new Date();
				if(m.get("timex")==null)
				{
					m.put("finishtime", "00:00");
					continue;
				}
				Date dt2 = timeUtil.addAsSecs(dt, (Integer) m.get("timex"));
				m.put("finishtime", timeUtil.geTime_NotIncluDate_HHmm_fmt(  dt2));
				
				System.out.println("...");
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		String jsonStrO88 = core.toJsonStrO88(li);
		System.out.println(jsonStrO88);
		return jsonStrO88;
	}
	
	public Object get_data() {
		
		
		List<Map> li = dx
				.execSql("select * from timer_tab  order by id limit 40 ");
		for (int i = 0; i < li.size(); i++) {
			try {
				Map m = li.get(i);
				Date dt = new Date();
				if(m.get("timex")==null)
				{
					m.put("finishtime", "00:00");
					continue;
				}
				Date dt2 = timeUtil.addAsSecs(dt, (Integer) m.get("timex"));
				m.put("finishtime", timeUtil.geTime_NotIncluDate_HHmm_fmt(  dt2));
				
				System.out.println("...");
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	//	String jsonStrO88 = core.toJsonStrO88(li);
	//	System.out.println(jsonStrO88);
		return li;
	}
	
	
//	function getTimerData()
//	{
//		date_default_timezone_set("Asia/Shanghai");
//		$sql="select * from timer_tab  order by id limit 40 ";
//			$result=mysql_query($sql,$GLOBALS["varsx"]["conn"]);
//			
//			while($r = mysql_fetch_array($result)) {
//			      $time_len=	$r["timex"];
//				//  print_r(  $time_len);
//				  $finish_time=time()+ $time_len;
//				  if(  $time_len=="0")
//				  {
//					  $GLOBALS["stack"][]="   time_len==0)  ";
//				 	  $finish_time="0";
//					    $r["finishtime"]="00:00" ;
//				  }else	
//				  {		  
//				 // print_r(	  $GLOBALS["stack"]);
//					  $r["finishtime"]=date("H:i",$finish_time) ;
//				  }
//				  // $finish_time;
//				  $li[]=$r;
//			}
//			return json_encode($li);
//		
//			//Date dt2 = timeUtil.addAsSecs(dt, (Integer) m.get("timex"));
//				//	m.put("finishtime", timeUtil.geTime_NotIncluDate_HHmm_fmt(  dt2));
//		
//	}

	public void setCaptch() {

		// String captchCode =capt.getTxt();
		//
		// String js=filex.read(pathx.classPath(Reg.class)+ "\\set_captch.js");
		// js=js.replaceAll("@capt", captchCode);
		// //"1234";
		// System.out.println("exe js:"+ js);
		// atiBrowserExampleinstance.browser.execute(js);

	}

	public static void execMeth_AysGui(final Runnable runnable, String string) {
		core.execMeth_Ays(new Runnable() {

			@SuppressWarnings("static-access")
			@Override
			public void run() {
				System.out.println("=-ajsy");
				// Display default1 = display.getDefault();
				// runnable.run();
				Display.getDefault().asyncExec(runnable);
				// display.asyncExec(runnable);
			}
		}, string);

	}

}
